package xiaoa.java.set;

import java.io.Closeable;
import java.io.IOException;
import java.util.HashSet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


/**
 * 一个具有TTL的set
 * @author xiaoa
 * @date 2018年1月27日 下午1:06:20
 * @version V1.0
 *
 * @param <E>
 */
public class TTlSet<E>  extends HashSet<E> implements Closeable{

	
	/**
	 * @Fields serialVersionUID : 
	 * @author xiaoa
	 */
	private static final long serialVersionUID = 1L;
	
	ScheduledExecutorService service = null;
	private long defaultTTL = 0;
	TimeUnit unit = null;
	
	
	private static  TTlSet<Object> defaultSet  = null;
	
	public static  TTlSet<Object> getInstance(){
		if(defaultSet == null){
			defaultSet = new TTlSet<>(0, null);
		}
		return defaultSet;
	}
	
	
	
	public TTlSet(long defaultTTL , TimeUnit unit ){
		service =  Executors.newScheduledThreadPool(1);
		this.defaultTTL = defaultTTL;
		this.unit = unit;
	}
	
	@Override
	public boolean add(E e) {
		
		if (defaultTTL <= 0 || unit == null){
			throw new RuntimeException(" defaultSet cannot  add(E e)");
		}
		
		return add(e , defaultTTL ,unit);
	}
	
	@SuppressWarnings("resource")
	public boolean add(final E e , long ttl , TimeUnit unit ) {
		final TTlSet<E> thisSet = this;
		Runnable  run = new Runnable() {
			
			@Override
			public void run() {
				
				if (thisSet.contains(e)){
					thisSet.remove(e);
				}
				
			}
		};
		
		service.schedule(run, ttl, unit);
		return super.add(e);
	}


	@Override
	public void close() throws IOException {
		service.shutdown();
	}
}
